package com.prs.crm.action.sale;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.action.FlowAction;
import com.prs.crm.annotation.Clew;
import com.prs.crm.annotation.FlowActive;
import com.prs.crm.annotation.FlowStart;
import com.prs.crm.context.Constrains;
import com.prs.crm.domain.fs.BankAccount;
import com.prs.crm.domain.fs.Detail;
import com.prs.crm.domain.purchase.FundsInBar;
import com.prs.crm.domain.sale.Returns;
import com.prs.crm.domain.sale.ReturnsDetail;
import com.prs.crm.domain.sale.ReturnsType;
import com.prs.crm.domain.sale.SalesContract;
import com.prs.crm.domain.sale.SalesContractDetail;
import com.prs.crm.domain.sale.SalesReceives;
import com.prs.crm.domain.sale.SalesShippingDetail;
import com.prs.crm.domain.stock.Product;
import com.prs.crm.domain.sys.Code;
import com.prs.crm.domain.sys.CodeInvoice;
import com.prs.crm.service.fs.BankAccountService;
import com.prs.crm.service.fs.DetailService;
import com.prs.crm.service.sale.ReturnsService;
import com.prs.crm.service.sale.ReturnsTypeService;
import com.prs.crm.service.sale.SalesContractService;
import com.prs.crm.service.sale.SalesShippingDetailService;
import com.prs.crm.service.sys.CodeInvoiceService;
import com.prs.crm.service.sys.CodeService;

public class ReturnsAction extends FlowAction<Returns> {

	private static final long serialVersionUID = 1L;

	private Returns returns;

	private String Encode;

	private CodeInvoice codeInvoice;

	private CodeInvoiceService codeInvoiceService;

	private Code code;

	private CodeService codeService;

	private Collection<CodeInvoice> codelist;

	private SalesContract salesContract;

	private Product[] products;

	private String[] pronames;

	private Double[] originalCosts;

	private Double[] nowCosts;

	private Integer[] returnsNums;

	private Double[] rebates;

	private String[] totalPrices;

	private ReturnsService returnsService;

	private ReturnsTypeService returnsTypeService;

	private SalesContractService salesContractService;

	private PaginationSupport pagination;

	private List<ReturnsType> typelist;

	private Collection<ReturnsDetail> slist;
	private Collection<BankAccount> bankAccounts;
	private BankAccountService bankAccountService;
	private FundsInBar fundsInBar;
	private DetailService detailService;

	private List<SalesContractDetail> contractDetails;
	private String batchNum;
	private SalesContractService contractService;
	private String listString;
	private double money;

	private List<SalesShippingDetail> salesShippingDetails = new ArrayList<SalesShippingDetail>();
	private SalesShippingDetailService salesShippingDetailService;
	private Product product;
	private String noReturnNum;
	private Integer[] returnResviceNum;
	private String[] detailAll;
	private Double payedMoney;
	private String salseConstractState;
	public String getSalseConstractState() {
		return salseConstractState;
	}

	public void setSalseConstractState(String salseConstractState) {
		this.salseConstractState = salseConstractState;
	}

	@FlowActive(target = "returns", flowservice = "returnsService")
	@Action("editReturns")
	public String editReturns() {
		this.codelist = this.getCodeInvoiceService()
				.getInvoiceCodeType("销售退货单");
		this.typelist = this.getReturnsTypeService().getAllType();
		return SUCCESS;
	}

	@Clew(results = { "success", "none" })
	@FlowStart(target = "returns", flowservice = "returnsService")
	@Action(value = "saveReturns", results = {
			@Result(name = "success", type = "redirect", location = "listReturns"),
			@Result(name = "error", type = "chain", location = "editReturns"),
			@Result(name = "none", type = "redirect", location = "listReturns") })
	public String saveReturns() {
		
//		if(Integer.parseInt(this.getSalseConstractState())==0){
//			System.out.println(salseConstractState);
//			this.addActionError("此销售合同没有进行发货");
//		}else{
			
		if ("n".equals(Encode)) {
			int EncodeRplice = this.getCodeService().getBackRpliceAll("手动编码",
					"销售退货", returns.getReturnCode());
			if (EncodeRplice != 0) {
				this.addActionError("编码重复!请重新输入");
				return ERROR;
			}
		}
		// if (returns.getSalesShipping() == null) {
		// this.addActionError("请添加关联发货单");
		// return ERROR;
		// }
		if (returns.getReturnCode() == null
				|| returns.getReturnCode().equals("")) {
			this.addActionError("请添加退货编号");
			return ERROR;
		}
		if (returns.getReturnName() == null
				|| returns.getReturnName().equals("")) {
			this.addActionError("请添加退货主题");
			return ERROR;
		}
		if (returns.getReturnState() == null
				|| returns.getReturnState().equals("")) {
			this.addActionError("请选择退货状态");
			return ERROR;
		}

		if (products == null || products.length == 0) {
			this.addActionError("商品不能为空");
			return ERROR;
		}

		/**
		 * 编码产生
		 */
		if ("n".equals(Encode)) {
			Code codes = new Code();
			codes.setCodeValue(returns.getReturnCode());
			codes.setCodeMolde("销售退货");
			codes.setEntityName(this.getClass().getName());
			codes.setCodeType("手动编码");
			this.getCodeService().save(codes);
			returns.setCode(codes);
			this.getReturnsService().saveReturns(returns, products, pronames,
					originalCosts, nowCosts, returnsNums, rebates, totalPrices,
					returnResviceNum, detailAll);
		} else {
			CodeInvoice Vob = this.getCodeInvoiceService().getVobject(
					codeInvoice.getId());
			Code codes = new Code();
			codes.setCodeValue(returns.getReturnCode());
			codes.setCodeMolde("销售退货");
			codes.setEntityName(this.getClass().getName());
			Vob.setNumBackUp(Increase(Vob.getNumBackUp()));
			this.getCodeInvoiceService().saveOrUpdate(Vob);
			codes.setCodeType(Vob.getCodePlan());
			this.getCodeService().save(codes);
			returns.setCode(codes);
			this.getReturnsService().saveReturns(returns, products, pronames,
					originalCosts, nowCosts, returnsNums, rebates, totalPrices,
					returnResviceNum, detailAll);
		}
		//}
		this.setPrompt("操作成功");
		return SUCCESS;

	}

	public static String Increase(String backupNum) {
		String Inc = "";
		int lengths = backupNum.length();
		String lengthss = (Integer.parseInt(backupNum) + 1) + "";
		int increase = (lengthss.trim()).length();
		if (lengths != increase) {
			String In = "";
			for (int i = 0; i < lengths - increase; i++) {
				In = In + "0";
			}
			In = (In + lengthss).trim();
			Inc = In;
		} else {
			Inc = lengthss;
		}
		return Inc.trim();
	}

	@Action("listReturns")
	public String excute() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Returns.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getReturnsService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listMoney")
	public String listMoney() {
		// moneyType
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Returns.class);
		criteria.createAlias("salesContract", "b");
		pagination = this.getPaginationHelper().prepare(pagination);
		criteria.add(Restrictions.gtProperty("b.payedMoney","b.money"));
		criteria.add(Restrictions.eq("moneyType", 0));
		criteria.add(Restrictions.eq("flowstatus", 2));
		this.setPagination(this.getReturnsService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("editMoney")
	public String editMoney() {
		this.bankAccounts = this.getBankAccountService().getAllBankAccount();
		this.money = 0.0;
		this.payedMoney=returns.getSalesContract().getPayedMoney()-returns.getSalesContract().getMoney();
		for (ReturnsDetail detail : returns.getDetails()) {
			money = money + detail.getTotalPrice();
		}
		return SUCCESS;
	}

	@Action(value = "submitMoney", results = { @Result(name = "success", type = "redirect", location = "listMoney") })
	public String submitMoney() {
		Double sum = this.getDetailService().getBalanceByAccount(
				fundsInBar.getBankAccount());
		Detail detialob = new Detail();
		// detialob.setFundsInBar(fundsInBar);
		detialob.setIncome(0.0);
		detialob.setPay(fundsInBar.getInMony());
		detialob.setBalance(sum - fundsInBar.getInMony());
		detialob.setBankAccount(fundsInBar.getBankAccount());
		detialob.setItem(Constrains.FS_ITEMS_SALESRETURNED);
		this.getDetailService().save(detialob);
		returns.setMoneyType(1);
		//returns.getSalesContract().setPayedMoney(returns.getSalesContract().getPayedMoney()-fundsInBar.getInMony());
		returns.getSalesContract().setMoney(returns.getSalesContract().getMoney()+fundsInBar.getInMony());
		
		this.getReturnsService().save(returns);
		return SUCCESS;
	}

	@Action("viewReturns")
	public String viewReturns() {
		returns = this.getReturnsService().get(returns.getId());
		this.slist = returns.getDetails();
		this.displayEndNodes(returns);
		return SUCCESS;
	}

	@Action("selectSalesContract")
	public String selectSalesContract() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SalesContract.class);

		// criteria.add(Restrictions.between("returnState", 0, 2));
		criteria.add(Restrictions.eq("flowstatus", 2));
		criteria.add(Restrictions.le("ShippingState", 0));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getSalesContractService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	/**
	 * 收款单关联合同查询
	 * 
	 * @return
	 */
	@Action("selectSalesContractReceives")
	public String selectSalesContractReceives() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SalesContract.class);
		// criteria.add(Restrictions.between("receivesState", 0, 1));
		criteria.add(Restrictions.le("receiptState", 0));
		criteria.add(Restrictions.eq("flowstatus", 2));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getSalesContractService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("selectSalesContractProduct")
	public String selectSalesContractProduct() {

		salesShippingDetails = this.getSalesShippingDetailService()
				.salesShippingDetails(returns.getSalesContract());
		// System.out.println(salesShippingDetails.size()+"  "+returns.getSalesContract().getId());
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SalesContractDetail.class);
		criteria.add(Restrictions.eq("salesContract", returns
				.getSalesContract()));
		criteria.add((Restrictions.eq("returnSate", 0)));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getSalesContractService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("selectSalesContractReturn")
	public String selectSalesContractReturn() {
		try {
			DetachedCriteria criteria = this.getPaginationHelper().createQuery(
					SalesShippingDetail.class);

			criteria.createAlias("salesShipping", "b");
			criteria.add(Restrictions.eq("product", product));
			criteria.add(Restrictions.eq("b.salesContract", salesContract));
			criteria.add(Restrictions.gtProperty("number", "retruenNum"));
			pagination = this.getPaginationHelper().prepare(pagination);
			this.setPagination(this.getSalesContractService().listByPage(
					criteria, pagination));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return SUCCESS;
	}

	@Action("selectSalesShippingProduct")
	public String selectSalesContractProduct1() {

		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SalesShippingDetail.class);
		criteria.add(Restrictions.eq("outState", 0));
		criteria.add(Restrictions.eq("salesShipping", returns
				.getSalesShipping()));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getSalesContractService().listByPage(criteria,
				pagination));

		return SUCCESS;
	}

	@Action("selectSalesContractProducts")
	public String selectSalesContractProducts() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SalesContractDetail.class);
		criteria.add(Restrictions.eq("salesContract", returns
				.getSalesContract()));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getSalesContractService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("selectProduct1")
	public String selectProduct1() {

		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SalesContractDetail.class);
		criteria.add(Restrictions.eq("salesContract", returns
				.getSalesContract()));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getSalesContractService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("selectProduct2")
	public String selectProduct2() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SalesContractDetail.class);
		criteria.add(Restrictions.eq("salesContract", returns
				.getSalesContract()));
		criteria.add(Restrictions.eq("recivesState", 0));

		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getSalesContractService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("updateReturns")
	public String updateReturns() {
		returns = this.getReturnsService().get(returns.getId());
		this.slist = returns.getDetails();
		this.displayEndNodes(returns);
		return SUCCESS;
	}

	@Clew(results = { "success", "none" })
	@FlowStart(target = "returns", flowservice = "returnsService")
	@Action(value = "saveUpdateReturns", results = {
			@Result(name = "success", type = "redirect", location = "listUpdateReturns"),
			@Result(name = "none", type = "redirect", location = "listUpdateReturns") })
	public String saveUpdateReturns() {

		Returns reObject = this.getReturnsService().getReturnObject(
				returns.getId());
		reObject.setReturnState(returns.getReturnState());
		this.getReturnsService().saveOrUpdate(reObject);
		this.setPrompt("变更操作成功");
		return SUCCESS;
	}

	@Action("listUpdateReturns")
	public String excute1() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Returns.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getReturnsService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	public Returns getReturns() {
		return returns;
	}

	public void setReturns(Returns returns) {
		this.returns = returns;
	}

	public Product[] getProducts() {
		return products;
	}

	public void setProducts(Product[] products) {
		this.products = products;
	}

	public String[] getPronames() {
		return pronames;
	}

	public void setPronames(String[] pronames) {
		this.pronames = pronames;
	}

	public Double[] getOriginalCosts() {
		return originalCosts;
	}

	public void setOriginalCosts(Double[] originalCosts) {
		this.originalCosts = originalCosts;
	}

	public Double[] getNowCosts() {
		return nowCosts;
	}

	public void setNowCosts(Double[] nowCosts) {
		this.nowCosts = nowCosts;
	}

	public Integer[] getReturnsNums() {
		return returnsNums;
	}

	public void setReturnsNums(Integer[] returnsNums) {
		this.returnsNums = returnsNums;
	}

	public Double[] getRebates() {
		return rebates;
	}

	public void setRebates(Double[] rebates) {
		this.rebates = rebates;
	}

	public String[] getTotalPrices() {
		return totalPrices;
	}

	public void setTotalPrices(String[] totalPrices) {
		this.totalPrices = totalPrices;
	}

	public ReturnsService getReturnsService() {
		return returnsService;
	}

	public void setReturnsService(ReturnsService returnsService) {
		this.returnsService = returnsService;
	}

	public ReturnsTypeService getReturnsTypeService() {
		return returnsTypeService;
	}

	public void setReturnsTypeService(ReturnsTypeService returnsTypeService) {
		this.returnsTypeService = returnsTypeService;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public Collection<ReturnsDetail> getSlist() {
		return slist;
	}

	public void setSlist(Collection<ReturnsDetail> slist) {
		this.slist = slist;
	}

	public List<ReturnsType> getTypelist() {
		return typelist;
	}

	public void setTypelist(List<ReturnsType> typelist) {
		this.typelist = typelist;
	}

	public SalesContractService getSalesContractService() {
		return salesContractService;
	}

	public void setSalesContractService(
			SalesContractService salesContractService) {
		this.salesContractService = salesContractService;
	}

	public SalesContract getSalesContract() {
		return salesContract;
	}

	public void setSalesContract(SalesContract salesContract) {
		this.salesContract = salesContract;
	}

	public String getBatchNum() {
		return batchNum;
	}

	public void setBatchNum(String batchNum) {
		this.batchNum = batchNum;
	}

	public List<SalesContractDetail> getContractDetails() {
		return contractDetails;
	}

	public void setContractDetails(List<SalesContractDetail> contractDetails) {
		this.contractDetails = contractDetails;
	}

	public SalesContractService getContractService() {
		return contractService;
	}

	public void setContractService(SalesContractService contractService) {
		this.contractService = contractService;
	}

	public String getListString() {
		return listString;
	}

	public void setListString(String listString) {
		this.listString = listString;
	}

	public String getEncode() {
		return Encode;
	}

	public void setEncode(String encode) {
		Encode = encode;
	}

	public CodeInvoice getCodeInvoice() {
		return codeInvoice;
	}

	public void setCodeInvoice(CodeInvoice codeInvoice) {
		this.codeInvoice = codeInvoice;
	}

	public CodeInvoiceService getCodeInvoiceService() {
		return codeInvoiceService;
	}

	public void setCodeInvoiceService(CodeInvoiceService codeInvoiceService) {
		this.codeInvoiceService = codeInvoiceService;
	}

	public Code getCode() {
		return code;
	}

	public void setCode(Code code) {
		this.code = code;
	}

	public CodeService getCodeService() {
		return codeService;
	}

	public void setCodeService(CodeService codeService) {
		this.codeService = codeService;
	}

	public Collection<CodeInvoice> getCodelist() {
		return codelist;
	}

	public void setCodelist(Collection<CodeInvoice> codelist) {
		this.codelist = codelist;
	}

	public Collection<BankAccount> getBankAccounts() {
		return bankAccounts;
	}

	public void setBankAccounts(Collection<BankAccount> bankAccounts) {
		this.bankAccounts = bankAccounts;
	}

	public FundsInBar getFundsInBar() {
		return fundsInBar;
	}

	public void setFundsInBar(FundsInBar fundsInBar) {
		this.fundsInBar = fundsInBar;
	}

	public BankAccountService getBankAccountService() {
		return bankAccountService;
	}

	public void setBankAccountService(BankAccountService bankAccountService) {
		this.bankAccountService = bankAccountService;
	}

	public DetailService getDetailService() {
		return detailService;
	}

	public void setDetailService(DetailService detailService) {
		this.detailService = detailService;
	}

	public double getMoney() {
		return money;
	}

	public void setMoney(double money) {
		this.money = money;
	}

	public List<SalesShippingDetail> getSalesShippingDetails() {
		return salesShippingDetails;
	}

	public void setSalesShippingDetails(
			List<SalesShippingDetail> salesShippingDetails) {
		this.salesShippingDetails = salesShippingDetails;
	}

	public SalesShippingDetailService getSalesShippingDetailService() {
		return salesShippingDetailService;
	}

	public void setSalesShippingDetailService(
			SalesShippingDetailService salesShippingDetailService) {
		this.salesShippingDetailService = salesShippingDetailService;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public String getNoReturnNum() {
		return noReturnNum;
	}

	public void setNoReturnNum(String noReturnNum) {
		this.noReturnNum = noReturnNum;
	}

	public Integer[] getReturnResviceNum() {
		return returnResviceNum;
	}

	public void setReturnResviceNum(Integer[] returnResviceNum) {
		this.returnResviceNum = returnResviceNum;
	}

	public String[] getDetailAll() {
		return detailAll;
	}

	public void setDetailAll(String[] detailAll) {
		this.detailAll = detailAll;
	}

	public Double getPayedMoney() {
		return payedMoney;
	}

	public void setPayedMoney(Double payedMoney) {
		this.payedMoney = payedMoney;
	}

}
